import os
import sys
import json
import random
from .cmd_args import manage_cmd_args 
from .source import connect_redis,obtain_model_from_redis
from .utils import Parser
from .observer import Subject,StatusObserver,ProgressObserver
from .solver import Desimulator
from .result_handle import DataProcess

def model_checking(argv=None):
    #sys.argv = ['main.py', '-ip', 'localhost', '-port', '6379', '-taskId','0001','-taskType','calcreq']
    args = manage_cmd_args(argv)
    redis_client = connect_redis(args)
    sim_args = obtain_model_from_redis(redis_client,args['taskId']+args['taskType'])
    dict = json.loads(sim_args)
    random.seed(dict['seed'])
    pms_model = None
    save_dir = os.path.join(dict['result_home'],args['taskId'])
    parser = Parser(dict['xmlfile'])
    errorMsg = ''
    errorMsg = parser.validate_xml()
    fb = {}
    if errorMsg:        
        fb['code']=1
    else:
        pms_model = parser.parse_xml_ET()        
        fb['code']=0
        
    fb['errorMsg']=errorMsg
    print(json.dumps(fb),flush=True)
    return args,dict, pms_model, save_dir

async def run_simulation(args,dict,pms_model,save_dir):
    redis_client = connect_redis(args)
    subject = Subject()
    status_observer = StatusObserver(redis_client,save_dir)
    process_observer = ProgressObserver(redis_client,save_dir)
    subject.register_observer(status_observer)
    subject.register_observer(process_observer)
    solver = Desimulator(dict['xmlfile'],subject,dict['simulate_times'],dict['timeslice'])
    results,result2 = solver.run(args['taskId'])
    dp = DataProcess(args['taskId'],subject,save_dir)
    dp.str2xml(pms_model,dict['timeslice'],dict['simulate_times'],results,result2)


async def main(argv=None):
    args,dict, pms_model, save_dir = model_checking(argv)
    if pms_model:
        await run_simulation(args,dict,pms_model,save_dir)